<script setup>
import { ref, watchEffect } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getBlogList } from '@/api/blogApi'
import usePageTitle from '@/hooks/usePageTitle'
import BlogCard from '@/components/BlogCard.vue'

usePageTitle('首页')

// // 定义 list total
const list = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSizeRef = ref(10)

const $route = useRoute()
const $router = useRouter()

// 使用 watchEffect监听url参数page、pageSize、category、keyword的变化，然后调用获取博客列表的接口
watchEffect(async () => {
  const query = $route.query
  currentPage.value = Number(query.page) || 1
  pageSizeRef.value = Number(query.pageSize) || 10

  const page = Number(query.page) || 1
  const pageSize = Number(query.pageSize) || 10
  const category = query.category || ''
  const keyword = query.keyword || ''
  const res = await getBlogList({ page, pageSize, category, keyword })
  list.value = res.list
  total.value = res.total
})

const handlePageChange = (page) => {
  const path = $route.path
  const query = { ...$route.query, page }
  $router.push({ path, query })
}
</script>

<template>
  <main>
    <div class="blog-container" v-for="item in list" :key="item.id">
      <BlogCard :blog="item" />
    </div>
    <div class="pagination">
      <el-pagination v-model="currentPage" :total="total" :page-size="pageSizeRef" layout="prev, pager, next"
        :pager-count="7"
        @current-change="handlePageChange"></el-pagination>
    </div>
  </main>
</template>

<style scoped>
.blog-container {
  margin-bottom: 16px;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>